// packageA/pages/trainReportCost/trainReportCost.js
const app = getApp();
import CommonService from '../../../utils/service/commonService.js';
import Toast from '../../../miniprogram_npm/@vant/weapp/toast/toast';
import Base64 from '../../../utils/Base64.js';
const util = require('../../../utils/util');

Page({

  /**
   * 页面的初始数据
   */
  data: {
    //传参
    paramObj:null,
    //传参来的id
    id:null,
    //修改信息回显
    editInfo:{},
    //提交按钮禁用
    disabled:false,
    //避免表单重复提交
    code:null,
    //费用对象
    costSet:{
      mileage: '',
      mileageCost: '',
      remark: '',
      subsidy: '',
      tollFee: '',
      trainingCost: ''
    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      code:Base64.encode(new Date() + app.globalData.userInfo.userName)
    })

    if(options.paramObj){
      let paramObj=JSON.parse(options.paramObj);
      console.log('传参');
      console.log(paramObj);

      this.setData({
        paramObj: paramObj
      })

      if(paramObj.id){
        this.setData({
          id: paramObj.id
        })
        //获取修改的数据
        this.getInfo();
      }
    }
  },

  //提交表单
  confirmForm(e){ 
    let td=this.data;
    let costList=td.costList;
    
    //验证是否是整数
    let flag=costList.some((item)=>{
      let ff=false;
      for(let key in item){
        if(key!='staff' && key!='remark' && item[key]){
          if(!(/^([0]|[1-9][0-9]*)$/.test(item[key]))){
            ff=true;
          }
        }
      }
      return ff;
    });

    if(flag){
      Toast.fail('请输入整数');
      return;
    }

    //计算总费用
    let total=0;
    costList.forEach(item => {
      item.total=Number(item.mileage) * Number(item.mileageCost) + Number(item.tollFee) + Number(item.subsidy) + Number(item.trainingCost);
      total+=item.total;
    });
    
    //工单记录
    let options=td.editInfo.options;
    if(td.editInfo.totalTrainingCosts!=total){
      options.push({
        content: app.globalData.userInfo.userName + ' 设置了费用',
        timestamp: util.timeFormat(new Date())
      });
    }

    let param={
      className:'trainingReport',
      data:{
        id: td.id,
        cost: td.costList,
        totalTrainingCosts: total,
        options: options
      }
    }

    //避免表单重复提交
    Toast.loading({
      duration: 0,
      forbidClick: true,
      message: '数据提交中...'
    });
    
    //console.log(param);

    CommonService.goSave(param).then(res=>{
      this.setData({
        disabled:false
      })
      if (res.statusCode == 200 && res.data.success == true){
        Toast.success('成功');
        setTimeout(() => {
          //返回列表页并刷新数据
          this.backAndRefresh();
        }, 1000);
      }else if(res.statusCode==202){
        Toast.fail('您操作太快了,请勿重复提交');
      }else{
        Toast.fail('操作失败');
      }
    }).catch((error) => {
      Toast.fail('操作失败');
    })  
  },

  //获取修改的数据
  getInfo(){
    let param = {
      isAuth: false,
      className: 'trainingReport',
      data: {
        id:this.data.id,
        selectFields: ['id','trainingStaff','oldTrainers','cost','totalTrainingCosts','state','trainType','options']
      }
    }

    CommonService.goFindList(param).then(res => {
      if(res.data.data && res.data.data.result && res.data.data.result.length) {
        let result=res.data.data.result[0];

        //人员
        let staffs=[];
        if(result.oldTrainers && result.oldTrainers.length){
          staffs=result.oldTrainers;
        }
        staffs.push(result.trainingStaff);

        //费用
        let costList=[];
        if(result.cost && result.cost.length){
          costList=result.cost;          
        }        

        if(staffs.length > costList.length){          
          staffs.forEach(item => {              
            for(let i=0;i<costList.length;i++){
              if(!costList[i].staff.changeTime && costList[i].staff.id==item.id){
                costList[i].staff.changeTime=item.changeTime;
              }  
            }                       
          });
          
          staffs.forEach(item => {
            if(!item.changeTime){
              costList.push({
                //人员
                staff:item,
                //培训费
                trainingCost: '',
                //公里数
                mileage: '',
                //公里/元
                mileageCost: '',
                //过路（桥）费
                tollFee: '',
                //补助
                subsidy: '',
                //总价
                total: '',
                //备注
                remark: ''  
              });
            }else if(item.changeTime){
              let flag = costList.every(el=>{
                return el.staff.id!=item.id;
              })
              if(flag){
                costList.push({
                  //人员
                  staff:item,
                  //培训费
                  trainingCost: '',
                  //公里数
                  mileage: '',
                  //公里/元
                  mileageCost: '',
                  //过路（桥）费
                  tollFee: '',
                  //补助
                  subsidy: '',
                  //总价
                  total: '',
                  //备注
                  remark: ''  
                });
              }
            } 
          });
        }

        console.log('人员');
        console.log(staffs);
        console.log('费用');
        console.log(costList);  

        this.setData({
          editInfo: result,
          costList: costList
        })  
      }
    }).catch((error) => {
    })
  },

  //获取输入的值
  onGetValue(e){ 
    let costList=this.data.costList;
    let dataset=e.currentTarget.dataset;
    let val=e.detail;
    
    costList.forEach(item => {
		  if(item.staff.changeTime==dataset.id){
        item[dataset.field]=val.trim();
      }
    });

    this.setData({ 
			costList: costList 
		})
  },

  //非空验证（field要先去掉空格）
  formNotEmpty(field,messageField,messageCon){
    if(!field){
      let obj = {};
      obj[messageField] = messageCon;
      obj['disabled'] = true;
      this.setData(obj);
      return false;
    }else{
      return true;
    }
  },

  //用户输入时清除错误提示
  clearMessage(e) {
    let field = e.target.dataset.message;
    let obj = {};
    obj[field] = "";
    obj['disabled'] = false;
    this.setData(obj);
  },  

  //返回列表页并刷新数据
  backAndRefresh(){
    let pages = getCurrentPages();
    let prevPage = pages[pages.length - 2];

    prevPage.getList();
    wx.navigateBack();
  }, 

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  }
})
